package io.wongd.lib_douyin.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import io.wongd.lib_douyin.Douyin;
import kotlin.jvm.functions.Function1;


public class DownloadUtil {

    public static class DownloadException extends Exception {
        public DownloadException(String message) {
            super(message);
        }
    }

    private static Context mContext;

    public static void init(Context ctx) {
        mContext = ctx;
    }

    private static Context getContext() {
        return mContext;
    }

    /**
     * 针对系统文夹只需要扫描,不用插入内容提供者,不然会重复
     *
     * @param filePath 文件路径
     */
    public static void scanFile(String filePath) {
        if (filePath.isEmpty()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(new File(filePath)));
        getContext().sendBroadcast(intent);
    }

    public static final String VIDEO_URL = "https://www.douyin.com/video/";

    public static final String NOTE_URL = "https://www.douyin.com/note/";

    public void downloadByClipboard() throws DownloadException {
        String clipboardData = ClipUtil.getClipboardData(getContext());
        if (clipboardData.isEmpty()) {
            T.show("剪切板内容为空");
            return;
        }
        String url = Douyin.INSTANCE.getShareLink(clipboardData);
        String awesomeUrl = Douyin.INSTANCE.getAwesomeUrl(url);
        Log.d("下载", "awesomeUrl = " + awesomeUrl);
        if (awesomeUrl.startsWith(VIDEO_URL)) {
            downloadVideo(awesomeUrl, new Function1<Integer, Void>() {
                @Override
                public Void invoke(Integer integer) {
                    Log.e("下载", "进度：" + integer);
                    return null;
                }
            });
        } else if (awesomeUrl.startsWith(NOTE_URL)) {
            downloadNote(awesomeUrl, new Function1<Integer, Void>() {
                @Override
                public Void invoke(Integer integer) {
                    Log.e("下载", "进度：" + integer);
                    return null;
                }
            });
        }
    }

    private void downloadNote(String awesomeUrl, Function1<Integer, Void> progressCallback) throws DownloadException {
        try {
            JSONObject data = Douyin.INSTANCE.getData(awesomeUrl);
            JSONObject awesomeInfo = Douyin.INSTANCE.getAwesomeInfo(data);
            downloadPicList(awesomeInfo, progressCallback);
        } catch (DownloadException e) {
            throw new DownloadException(e.getMessage());
        }
    }

    private void downloadPicList(JSONObject awesomeInfo, Function1<Integer, Void> progressCallback) throws DownloadException {
        JSONObject detail = awesomeInfo.getJSONObject("aweme").getJSONObject("detail");
        String title = detail.getStr("desc");
        JSONArray images = detail.getJSONArray("images");

        try {
            for (int index = 0; index < images.size(); index++) {
                int count = index + 1;
                JSONObject image = (JSONObject) images.get(index);
                JSONArray urlList = image.getJSONArray("urlList");
                downloadPicItem(title, count, urlList.get(urlList.size() - 1).toString());
                int progress = (int) (count * 100.0 / images.size());
//                observableEmitter.onNext(progress);
                progressCallback.invoke(progress);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    private void downloadPicItem(String title, int count, String picUrl) throws DownloadException {
        try {
            // 将匹配到的非法字符以空替换
            title = RegexUtil.replaceTitle(title);
            Connection.Response document = Jsoup.connect(picUrl).ignoreContentType(true).maxBodySize(0).timeout(0).execute();
            BufferedInputStream inputStream = document.bodyStream();
            File appDir = new File(Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "Camera" + File.separator);
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File fileSavePath = new File(appDir, title + "_" + count + ".jpeg");
            // 如果保存文件夹不存在,那么则创建该文件夹
            File fileParent = fileSavePath.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            if (fileSavePath.exists()) { //如果文件存在，则删除原来的文件
                fileSavePath.delete();
            }
            FileOutputStream fs = new FileOutputStream(fileSavePath);
            byte[] buffer = new byte[8 * 1024];
            int byteRead;
            while ((byteRead = inputStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteRead);
            }
            inputStream.close();
            fs.close();
            scanFile(fileSavePath.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            throw new DownloadException(e.getMessage());
        }
    }

    public void downloadVideo(String awesomeUrl, Function1<Integer, Void> progressCallback) throws DownloadException {
        JSONObject data = Douyin.INSTANCE.getData(awesomeUrl);
        JSONObject awesomeInfo = Douyin.INSTANCE.getAwesomeInfo(data);
        download(awesomeInfo, progressCallback);
    }

    private void download(JSONObject awesomeInfo, Function1<Integer, Void> progressCallback) throws DownloadException {
        JSONObject detail = awesomeInfo.getJSONObject("aweme").getJSONObject("detail");
        String playApi = detail.getJSONObject("video").getStr("playApi");
        String title = detail.getStr("desc");
        playApi = "https:" + playApi;
        try {
            title = RegexUtil.replaceTitle(title);
            Connection.Response document = Jsoup.connect(playApi).ignoreContentType(true).maxBodySize(0).timeout(0).execute();
            BufferedInputStream intputStream = document.bodyStream();
            int contentLength = Integer.parseInt(document.header("Content-Length"));
            File appDir = new File(Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "Camera" + File.separator);
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            File fileSavePath = new File(appDir, title + ".mp4");
            // 如果保存文件夹不存在,那么则创建该文件夹
            File fileParent = fileSavePath.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            if (fileSavePath.exists()) { //如果文件存在，则删除原来的文件
                fileSavePath.delete();
            }
            FileOutputStream fs = new FileOutputStream(fileSavePath);
            byte[] buffer = new byte[8 * 1024];
            int byteRead;
            int count = 0;
            while ((byteRead = intputStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteRead);
                count += byteRead;
                int progress = (int) (count * 100.0 / contentLength);
                progressCallback.invoke(progress);
            }
            intputStream.close();
            fs.close();
            scanFile(fileSavePath.getAbsolutePath());
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new DownloadException(exception.getMessage());
        }
    }

}
